package main.java.com.healthy.controller;
import main.java.com.healthy.entity.User;
import main.java.com.healthy.service.AuthService;
import main.java.com.healthy.service.UserProfileService;
import main.java.com.healthy.service.impl.AuthServiceImpl;
import main.java.com.healthy.service.impl.UserProfileServiceImpl;
import main.java.com.healthy.util.InputValidator;

import java.time.LocalDate;
import java.util.Scanner;

/**
 * 主控制器 - 负责系统入口和用户导航
 */
public class MainController {
    private AuthService authService;
    private UserProfileService profileService;
    private UserProfileController profileController;
    private FoodController foodController;
    private DietController dietController;
    private ReportController reportController;

    private User currentUser;
    private Scanner scanner;

    public MainController() {
        this.authService = new AuthServiceImpl();
        this.profileService = new UserProfileServiceImpl();
        this.profileController = new UserProfileController();
        this.foodController = new FoodController();
        this.dietController = new DietController();
        this.reportController = new ReportController();
        this.scanner = new Scanner(System.in);
    }

    /**
     * 启动系统
     */
    public void start() {
        System.out.println("==========================================");
        System.out.println("        欢迎使用健康饮食管理系统");
        System.out.println("==========================================");

        while (true) {
            if (currentUser == null) {
                showWelcomeMenu();
            } else {
                showMainMenu();
            }
        }
    }

    /**
     * 显示欢迎菜单（未登录状态）
     */
    private void showWelcomeMenu() {
        System.out.println("\n=== 主菜单 ===");
        System.out.println("1. 用户登录");
        System.out.println("2. 用户注册");
        System.out.println("3. 退出系统");
        System.out.print("请选择操作: ");

        String choice = scanner.nextLine().trim();

        switch (choice) {
            case "1":
                login();
                break;
            case "2":
                register();
                break;
            case "3":
                exitSystem();
                break;
            default:
                System.out.println("无效选择，请重新输入！");
        }
    }

    /**
     * 用户登录
     */
    private void login() {
        System.out.println("\n=== 用户登录 ===");

        int attempts = 0;
        final int MAX_ATTEMPTS = 3;

        while (attempts < MAX_ATTEMPTS) {
            System.out.print("请输入用户名: ");
            String username = scanner.nextLine().trim();

            System.out.print("请输入密码: ");
            String password = scanner.nextLine().trim();

            if (username.isEmpty() || password.isEmpty()) {
                System.out.println("用户名和密码不能为空！");
                attempts++;
                continue;
            }

            User user = authService.login(username, password);
            if (user != null) {
                currentUser = user;
                System.out.println("登录成功！欢迎 " + user.getUsername() + "！");
                return;
            } else {
                attempts++;
                System.out.println("用户名或密码错误！剩余尝试次数: " + (MAX_ATTEMPTS - attempts));
            }
        }

        System.out.println("登录失败次数过多，返回主菜单。");
    }

    /**
     * 用户注册
     */
    private void register() {
        System.out.println("\n=== 用户注册 ===");

        // 用户名
        String username;
        while (true) {
            System.out.print("请输入用户名: ");
            username = scanner.nextLine().trim();

            if (username.isEmpty()) {
                System.out.println("用户名不能为空！");
                continue;
            }

            if (!InputValidator.validateUsername(username)) {
                System.out.println("用户名格式不正确！只能包含字母、数字和下划线，长度3-20位");
                continue;
            }

            if (!authService.isUsernameAvailable(username)) {
                System.out.println("用户名已存在，请重新输入！");
                continue;
            }

            break;
        }

        // 密码
        String password;
        while (true) {
            System.out.print("请输入密码: ");
            password = scanner.nextLine().trim();

            if (password.isEmpty()) {
                System.out.println("密码不能为空！");
                continue;
            }

            if (!InputValidator.validatePassword(password)) {
                System.out.println("密码强度不足！密码长度至少6位，包含字母和数字");
                continue;
            }

            System.out.print("请确认密码: ");
            String confirmPassword = scanner.nextLine().trim();

            if (!password.equals(confirmPassword)) {
                System.out.println("两次输入的密码不一致！");
                continue;
            }

            break;
        }

        // 基础信息
        System.out.print("请输入身高(cm): ");
        double height = getValidDoubleInput(100, 250);

        System.out.print("请输入体重(kg): ");
        double weight = getValidDoubleInput(30, 200);

        System.out.print("请输入性别(男/女): ");
        String gender = getValidGenderInput();

        System.out.print("请输入年龄: ");
        int age = getValidIntInput(10, 100);

        System.out.println("请选择活动水平:");
        System.out.println("1. 久坐（办公室工作，很少运动）");
        System.out.println("2. 轻度活动（每周1-3天轻度运动）");
        System.out.println("3. 中度活动（每周3-5天中度运动）");
        System.out.println("4. 重度活动（每周6-7天高强度运动）");
        System.out.println("5. 极重度活动（体力劳动者或专业运动员）");
        System.out.print("请选择(1-5): ");

        String activityLevel;
        int activityChoice = getValidIntInput(1, 5);
        switch (activityChoice) {
            case 1: activityLevel = "久坐"; break;
            case 2: activityLevel = "轻度活动"; break;
            case 3: activityLevel = "中度活动"; break;
            case 4: activityLevel = "重度活动"; break;
            case 5: activityLevel = "极重度活动"; break;
            default: activityLevel = "中度活动";
        }

        System.out.println("请选择目标:");
        System.out.println("1. 减重");
        System.out.println("2. 维持");
        System.out.println("3. 增肌");
        System.out.print("请选择(1-3): ");

        String target;
        int targetChoice = getValidIntInput(1, 3);
        switch (targetChoice) {
            case 1: target = "减重"; break;
            case 2: target = "维持"; break;
            case 3: target = "增肌"; break;
            default: target = "维持";
        }

        // 创建用户对象
        User newUser = new User();
        newUser.setUsername(username);
        newUser.setPassword(password);
        newUser.setHeight(height);
        newUser.setWeight(weight);
        newUser.setGender(gender);
        newUser.setAge(age);
        newUser.setActivityLevel(activityLevel);
        newUser.setTarget(target);
        newUser.calculateBMI();

        // 注册用户
        if (authService.register(newUser)) {
            System.out.println("注册成功！");
            System.out.println("您的BMI: " + String.format("%.1f", newUser.getBmi()) +
                    " (" + newUser.getBmiCategory() + ")");

            // 自动登录
            currentUser = authService.login(username, password);
        } else {
            System.out.println("注册失败，请稍后重试！");
        }
    }

    /**
     * 显示主菜单（已登录状态）
     */
    private void showMainMenu() {
        System.out.println("\n=== 健康饮食管理系统 ===");
        System.out.println("当前用户: " + currentUser.getUsername());
        System.out.println("1. 个人档案管理");
        System.out.println("2. 食物数据库管理");
        System.out.println("3. 饮食记录管理");
        System.out.println("4. 营养报告查看");
        System.out.println("5. 健康建议查看");
        System.out.println("6. 用户设置");
        System.out.println("7. 退出登录");
        System.out.println("8. 退出系统");
        System.out.print("请选择操作: ");

        String choice = scanner.nextLine().trim();

        switch (choice) {
            case "1":
                profileController.manageUserProfile(currentUser);
                break;
            case "2":
                foodController.manageFoods(currentUser);
                break;
            case "3":
                dietController.manageDietRecords(currentUser);
                break;
            case "4":
                reportController.generateReports(currentUser);
                break;
            case "5":
                viewHealthAdvices();
                break;
            case "6":
                userSettings();
                break;
            case "7":
                logout();
                break;
            case "8":
                exitSystem();
                break;
            default:
                System.out.println("无效选择，请重新输入！");
        }
    }

    /**
     * 查看健康建议
     */
    private void viewHealthAdvices() {
        System.out.println("\n=== 健康建议 ===");
        // 这里可以调用 HealthAdviceService 获取建议
        System.out.println("功能开发中...");
        System.out.println("按回车键返回主菜单...");
        scanner.nextLine();
    }

    /**
     * 用户设置
     */
    private void userSettings() {
        System.out.println("\n=== 用户设置 ===");
        System.out.println("1. 修改密码");
        System.out.println("2. 返回主菜单");
        System.out.print("请选择: ");

        String choice = scanner.nextLine().trim();

        if ("1".equals(choice)) {
            changePassword();
        }
    }

    /**
     * 修改密码
     */
    private void changePassword() {
        System.out.print("请输入当前密码: ");
        String currentPassword = scanner.nextLine().trim();

        if (!authService.validatePassword(currentUser.getUsername(), currentPassword)) {
            System.out.println("当前密码错误！");
            return;
        }

        String newPassword;
        while (true) {
            System.out.print("请输入新密码: ");
            newPassword = scanner.nextLine().trim();

            if (!InputValidator.validatePassword(newPassword)) {
                System.out.println("密码强度不足！密码长度至少6位，包含字母和数字");
                continue;
            }

            System.out.print("请确认新密码: ");
            String confirmPassword = scanner.nextLine().trim();

            if (!newPassword.equals(confirmPassword)) {
                System.out.println("两次输入的密码不一致！");
                continue;
            }

            break;
        }

        if (authService.changePassword(currentUser.getUserId(), currentPassword, newPassword)) {
            System.out.println("密码修改成功！");
        } else {
            System.out.println("密码修改失败！");
        }
    }

    /**
     * 退出登录
     */
    private void logout() {
        System.out.println("用户 " + currentUser.getUsername() + " 已退出登录");
        currentUser = null;
    }

    /**
     * 退出系统
     */
    private void exitSystem() {
        System.out.println("感谢使用健康饮食管理系统，再见！");
        System.exit(0);
    }

    // 辅助方法

    /**
     * 获取有效的双精度浮点数输入
     */
    private double getValidDoubleInput(double min, double max) {
        while (true) {
            try {
                String input = scanner.nextLine().trim();
                double value = Double.parseDouble(input);
                if (value >= min && value <= max) {
                    return value;
                } else {
                    System.out.print("输入值应在 " + min + " 到 " + max + " 之间，请重新输入: ");
                }
            } catch (NumberFormatException e) {
                System.out.print("请输入有效的数字: ");
            }
        }
    }

    /**
     * 获取有效的整数输入
     */
    private int getValidIntInput(int min, int max) {
        while (true) {
            try {
                String input = scanner.nextLine().trim();
                int value = Integer.parseInt(input);
                if (value >= min && value <= max) {
                    return value;
                } else {
                    System.out.print("输入值应在 " + min + " 到 " + max + " 之间，请重新输入: ");
                }
            } catch (NumberFormatException e) {
                System.out.print("请输入有效的整数: ");
            }
        }
    }

    /**
     * 获取有效的性别输入
     */
    private String getValidGenderInput() {
        while (true) {
            String input = scanner.nextLine().trim();
            if ("男".equals(input) || "女".equals(input)) {
                return input;
            } else {
                System.out.print("请输入'男'或'女': ");
            }
        }
    }
}